import urlConfig from './config.js'

import {
	formatGetUri
} from './util.js'

const request = {}
const headers = {
	Authorization: uni.getStorageSync('token'),
}


request.globalRequest = (url, method, data, loading = true) => {
	headers.Authorization = uni.getStorageSync('token')
	if (loading) {
		uni.showLoading({
			title: '加载中'
		});
	}
	let requestUrl = urlConfig.url_config;
	return uni.request({
		url: requestUrl + url,
		method,
		data: data,
		header: {
		    'content-type': 'application/json'  
		}, 
		dataType: 'json',
		header: headers
	}).then(res => {
		uni.hideLoading();
		const resData = res[1].data
		if (res[1].statusCode == 200) {
			if(resData.hasOwnProperty('code')){
				if (resData.code != 200) {
					uni.showToast({
						title: resData.message,
						icon: "none",
						duration: 2000
					})
					throw resData.message
				}else{
					return resData.data;
				}
			}else{
				return resData
			}
		} else if(res[1].statusCode == 401){
			uni.removeStorageSync("token")
			uni.showToast({
				title: resData.error_description,
				icon: "none",
				duration: 2000
			})
			throw resData.error_description
		}else if(res[1].statusCode == 400){
			uni.showToast({
				title: '密码错误',
				icon: "none",
				duration: 2000
			})
			throw resData
		}
		else {
			throw resData
		}
	}).catch(parmas => {
		console.log('12 = '+parmas);
		uni.hideLoading();
		uni.showToast({
			title: message,
			icon: 'none'
		})
		throw parmas.message
	})
}


export default request
